﻿using System;
using System.Web.UI.WebControls;

namespace MyCommon.WebControls
{
    /// <summary>
    /// 下拉框方式的分页字段
    /// </summary>
    public class DropDownPageNumPagerField : System.Web.UI.WebControls.DataPagerField
    {
        /// <summary>
        /// 在派生类中重写时，为数据页导航字段对象创建用户界面 (UI) 控件并将它们添加到指定的容器。
        /// </summary>
        /// <param name="container">用来存储控件的容器。</param>
        /// <param name="startRowIndex">页面中第一条记录的索引。</param>
        /// <param name="maximumRows">单个页面上的最大项数。</param>
        /// <param name="totalRowCount">总项数。</param>
        /// <param name="fieldIndex">数据页导航字段在 System.Web.UI.WebControls.DataPager.Fields 集合中的索引。</param>
        public override void CreateDataPagers(System.Web.UI.WebControls.DataPagerFieldItem container, int startRowIndex, int maximumRows, int totalRowCount, int fieldIndex)
        {
            this.TrackViewState();
            var temp = DataPager.Page.IsPostBack;
            DropDownList ctrl = new DropDownList();
            int pageCount = (totalRowCount - 1) / maximumRows + 1;
            for (int i = 0; i < pageCount; i++)
            {
                ctrl.Items.Add(new ListItem(Convert.ToString(i + 1)));
            }
            ctrl.SelectedValue = Convert.ToString( startRowIndex / maximumRows + 1);
            ctrl.SelectedIndexChanged += new EventHandler(ctrl_SelectedIndexChanged);
            ctrl.AutoPostBack = true;
            container.Controls.Add(new Literal() { Text = "转到第" });
            container.Controls.Add(ctrl);
            container.Controls.Add(new Literal() { Text = "页" });
        }

        void ctrl_SelectedIndexChanged(object sender, EventArgs e)
        {
            int pageIndex = int.Parse((sender as DropDownList).SelectedValue);
            DataPager.SetPageProperties(DataPager.PageSize * (pageIndex - 1), DataPager.PageSize, true);
        }
        /// <summary>
        /// 在派生类中重写时，创建从 System.Web.UI.WebControls.DataPagerField 派生的空对象。
        /// </summary>
        /// <returns>从 System.Web.UI.WebControls.DataPagerField 派生的空对象。</returns>
        protected override System.Web.UI.WebControls.DataPagerField CreateField()
        {
            return new DropDownPageNumPagerField();
        }
        /// <summary>
        /// 在派生类中重写时，处理在数据页导航字段对象中发生的事件。
        /// </summary>
        /// <param name="e">事件数据。</param>
        public override void HandleEvent(System.Web.UI.WebControls.CommandEventArgs e)
        {
            throw new NotImplementedException();
        }
    }
}
